using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using RiceShop.Models;

namespace RiceShop
{
    public class ApplicationDbContext : DbContext
    {
        private readonly IConfiguration _configuration;

        public ApplicationDbContext(IConfiguration configuration, DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
            _configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                // 使用配置文件中的连接字符串配置数据库
                optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
            }
        }

        public DbSet<Admin> Admins { get; set; }
        public DbSet<Role> Roles { get; set; }  // 添加 Roles DbSet
        public DbSet<Menu> Menus { get; set; }
        public DbSet<AdminRole> AdminRoles { get; set; }
        public DbSet<RoleMenu> RoleMenus { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Brand> Brands { get; set; }
        public DbSet<Good> Goods { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<SKU> Skus { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderGoods> OrderGoods { get; set; }
        public DbSet<Cart> Carts { get; set; } = null!;
        public DbSet<Coupon> Coupons { get; set; }
        public DbSet<UserCoupon> UserCoupons { get; set; }
        public DbSet<Spec> Specs { get; set; }
        public DbSet<SpecValue> SpecValues { get; set; }
        public DbSet<PaymentRecord> PaymentRecords { get; set; }
        public DbSet<RefundRecord> RefundRecords { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Admin>(entity =>
            {
                // 确保表名设置正确
                entity.ToTable("SysAdmin"); // 显式设置表名

                // 设置 AdminCtime 的默认值为当前时间戳
                entity.Property(e => e.adminCtime)
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");

                // 设置 AdminUtime 的默认值为当前时间戳，并在添加或更新时生成值
                entity.Property(e => e.adminUtime)
                    .HasDefaultValueSql("CURRENT_TIMESTAMP")
                    .ValueGeneratedOnAddOrUpdate();
            });

            // 配置 Role 实体
            modelBuilder.Entity<Role>(entity =>
            {
                entity.ToTable("SysRole");  // 修改为 SysRole
                entity.HasKey(e => e.roleId);

                entity.Property(e => e.roleName)
                    .IsRequired()
                    .HasMaxLength(256);

                entity.Property(e => e.roleNormalizedName)
                    .HasMaxLength(256);
            });

            // 可以添加一些种子数据
            modelBuilder.Entity<Role>().HasData(
                new Role
                {
                    roleId = 1,
                    roleName = "管理员",
                    roleNormalizedName = "ADMIN",
                    roleConcurrencyStamp = Guid.NewGuid().ToString()
                },
                new Role
                {
                    roleId = 2,
                    roleName = "用户",
                    roleNormalizedName = "USER",
                    roleConcurrencyStamp = Guid.NewGuid().ToString()
                }
            );

            modelBuilder.Entity<AdminRole>(entity =>
            {
                entity.ToTable("SysAdminRole");
                entity.HasKey(e => new { e.adminId, e.roleId });
            });

            modelBuilder.Entity<RoleMenu>(entity =>
            {
                entity.ToTable("SysRoleMenu");
                entity.HasKey(e => new { e.roleId, e.menuId });
            });

            // 配置 Good 实体关系
            modelBuilder.Entity<Good>(entity =>
            {
                entity.ToTable("Good");
                entity.HasKey(e => e.SpuId);

                // Good 与 SKU 的一对多关系
                entity.HasMany(g => g.Skus)
                      .WithOne(s => s.Good)
                      .HasForeignKey(s => s.SpuId)
                      .OnDelete(DeleteBehavior.Cascade);

                // Good 与 Spec 的一对多关系
                entity.HasMany(g => g.Specs)
                      .WithOne()
                      .HasForeignKey(s => s.SpuId)
                      .OnDelete(DeleteBehavior.Cascade);

                // Good 与 SpecValue 的一对多关系
                entity.HasMany(g => g.SpecValues)
                      .WithOne()
                      .HasForeignKey(sv => sv.SpuId)
                      .OnDelete(DeleteBehavior.Cascade);
            });

            // 配置 Spec 实体关系
            modelBuilder.Entity<Spec>(entity =>
            {
                entity.ToTable("Spec");
                entity.HasKey(e => e.SpecId);

                // Spec 与 SpecValue 的一对多关系
                entity.HasMany<SpecValue>()
                      .WithOne()
                      .HasForeignKey(sv => sv.SpecId)
                      .OnDelete(DeleteBehavior.Cascade);

                // Spec 与 Good 的多对一关系
                entity.HasOne<Good>()
                      .WithMany(g => g.Specs)
                      .HasForeignKey(s => s.SpuId)
                      .OnDelete(DeleteBehavior.Cascade);
            });

            // 配置 SpecValue 实体关系
            modelBuilder.Entity<SpecValue>(entity =>
            {
                entity.ToTable("SpecValue");
                entity.HasKey(e => e.ValueId);

                // SpecValue 与 Spec 的多对一关系
                entity.HasOne<Spec>()
                      .WithMany()
                      .HasForeignKey(sv => sv.SpecId)
                      .OnDelete(DeleteBehavior.Cascade);

                // SpecValue 与 Good 的多对一关系
                entity.HasOne<Good>()
                      .WithMany(g => g.SpecValues)
                      .HasForeignKey(sv => sv.SpuId)
                      .OnDelete(DeleteBehavior.Cascade);
            });

            // 配置 SKU 实体关系
            modelBuilder.Entity<SKU>(entity =>
            {
                entity.ToTable("SKU");
                entity.HasKey(e => e.SkuId);
            });

            modelBuilder.Entity<User>(entity =>
            {
                entity.ToTable("User");
                
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).HasColumnName("id");
                
                entity.Property(e => e.OpenId)
                    .IsRequired()
                    .HasColumnName("openId")
                    .HasMaxLength(100);
                    
                entity.Property(e => e.NickName)
                    .HasColumnName("nickName")
                    .HasMaxLength(50);
                    
                entity.Property(e => e.AvatarUrl)
                    .HasColumnName("avatarUrl")
                    .HasMaxLength(500);
                    
                entity.Property(e => e.Gender)
                    .HasColumnName("gender");
                    
                entity.Property(e => e.Country)
                    .HasColumnName("country")
                    .HasMaxLength(50);
                    
                entity.Property(e => e.Province)
                    .HasColumnName("province")
                    .HasMaxLength(50);
                    
                entity.Property(e => e.City)
                    .HasColumnName("city")
                    .HasMaxLength(50);
                    
                entity.Property(e => e.PhoneNumber)
                    .HasColumnName("phoneNumber")
                    .HasMaxLength(20);
                    
                entity.Property(e => e.CreateTime)
                    .HasColumnName("createTime")
                    .HasDefaultValueSql("GETDATE()");
                    
                entity.Property(e => e.UpdateTime)
                    .HasColumnName("updateTime")
                    .HasDefaultValueSql("GETDATE()");
                    
                entity.Property(e => e.LastLoginTime)
                    .HasColumnName("lastLoginTime")
                    .HasDefaultValueSql("GETDATE()");
                    
                entity.Property(e => e.Status)
                    .HasColumnName("status")
                    .HasDefaultValue(1);
                    
                entity.Property(e => e.IsDeleted)
                    .HasColumnName("isDeleted")
                    .HasDefaultValue(false);
            });

            // 配置 Cart 实体关系
            modelBuilder.Entity<Cart>(entity =>
            {
                entity.ToTable("Cart");
                entity.HasKey(e => e.Id);

                // Cart 与 Good 的关系
                entity.HasOne(c => c.Good)
                      .WithMany()
                      .HasForeignKey(c => c.SpuId)
                      .OnDelete(DeleteBehavior.Restrict);

                // Cart 与 SKU 的关系
                entity.HasOne(c => c.SKU)
                      .WithMany()
                      .HasForeignKey(c => c.SkuId)
                      .OnDelete(DeleteBehavior.Restrict);
            });

            // Comment 配置
            modelBuilder.Entity<Comment>(entity =>
            {
                entity.ToTable("Comment");
                entity.HasKey(e => e.Id);
                
                // 配置与 Order 的多对一关系，使用 OrderId 作为外键
                entity.HasOne(c => c.Order)
                    .WithMany(o => o.Comments)
                    .HasForeignKey(c => c.OrderId)
                    .OnDelete(DeleteBehavior.Restrict);

                entity.Property(e => e.OrderNo)
                    .IsRequired()
                    .HasMaxLength(50);

                // 配置与 User 的关系
                entity.HasOne(c => c.User)
                    .WithMany()
                    .HasForeignKey(c => c.UserId)
                    .OnDelete(DeleteBehavior.Restrict);

                // 配置与 Good 的关系
                entity.HasOne(c => c.Good)
                    .WithMany()
                    .HasForeignKey(c => c.GoodId)
                    .OnDelete(DeleteBehavior.Restrict);
            });

            // OrderGoods 配置
            modelBuilder.Entity<OrderGoods>(entity =>
            {
                entity.ToTable("OrderGoods");
                entity.HasKey(e => e.Id);

                // 配置与 Order 的多对一关系
                entity.HasOne<Order>()
                    .WithMany(o => o.Items)
                    .HasForeignKey(og => og.OrderId)
                    .OnDelete(DeleteBehavior.Restrict);

                entity.Property(e => e.OrderNo)
                    .IsRequired()
                    .HasMaxLength(50);
            });

            // Order 配置
            modelBuilder.Entity<Order>(entity =>
            {
                entity.ToTable("Order");
                entity.HasKey(e => e.Id);
                
                entity.Property(e => e.OrderNo)
                    .IsRequired()
                    .HasMaxLength(50);

                // 配置与 OrderGoods 的一对多关系
                entity.HasMany(o => o.Items)
                    .WithOne()
                    .HasForeignKey(og => og.OrderId);
            });

            // PaymentRecord 配置
            modelBuilder.Entity<PaymentRecord>(entity =>
            {
                entity.ToTable("PaymentRecords");
                entity.HasKey(e => e.PaymentId);

                entity.Property(e => e.OrderNo)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.PaymentNo)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.PaymentMethod)
                    .HasMaxLength(20);

                entity.Property(e => e.PrepayId)
                    .HasMaxLength(50);

                entity.Property(e => e.TransactionId)
                    .HasMaxLength(50);

                entity.Property(e => e.FailReason)
                    .HasMaxLength(200);

                entity.Property(e => e.PaymentAmount)
                    .HasColumnType("decimal(18,2)");

                entity.Property(e => e.CreateTime)
                    .HasDefaultValueSql("GETDATE()");

                entity.Property(e => e.UpdateTime)
                    .HasDefaultValueSql("GETDATE()");

                // 配置与 Order 的关系
                entity.HasOne(p => p.Order)
                    .WithMany()
                    .HasForeignKey(p => p.OrderId)
                    .OnDelete(DeleteBehavior.Restrict);

                // 创建索引
                entity.HasIndex(e => e.OrderNo);
                entity.HasIndex(e => e.PaymentNo);
                entity.HasIndex(e => e.CreateTime);
                entity.HasIndex(e => e.PaymentStatus);
            });

            // RefundRecord 配置
            modelBuilder.Entity<RefundRecord>(entity =>
            {
                entity.ToTable("RefundRecords");
                entity.HasKey(e => e.RefundId);

                entity.Property(e => e.OrderNo)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.RefundNo)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.RefundReason)
                    .HasMaxLength(500);

                entity.Property(e => e.WxRefundId)
                    .HasMaxLength(100);

                entity.Property(e => e.RefundAmount)
                    .HasColumnType("decimal(18,2)");

                entity.Property(e => e.CreateTime)
                    .HasDefaultValueSql("GETDATE()");

                entity.Property(e => e.UpdateTime)
                    .HasDefaultValueSql("GETDATE()");

                // 配置与 Order 的关系
                entity.HasOne(r => r.Order)
                    .WithMany()
                    .HasForeignKey(r => r.OrderId)
                    .OnDelete(DeleteBehavior.Restrict);

                // 配置与 PaymentRecord 的关系
                entity.HasOne(r => r.PaymentRecord)
                    .WithMany()
                    .HasForeignKey(r => r.PaymentId)
                    .OnDelete(DeleteBehavior.Restrict);

                // 创建索引
                entity.HasIndex(e => e.OrderNo);
                entity.HasIndex(e => e.RefundNo);
                entity.HasIndex(e => e.PaymentId);
                entity.HasIndex(e => e.CreateTime);
                entity.HasIndex(e => e.RefundStatus);
            });
        }
    }
}
